<template>
  <div class="product-management-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>商品管理</h2>
      <el-button type="primary" @click="showAddDialog" :disabled="!canManage">
        <el-icon><Plus /></el-icon>
        添加商品
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索商品名称或分类..."
        style="width: 300px; margin-right: 10px"
        @input="handleSearch"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      
      <el-select v-model="categoryFilter" placeholder="选择分类" clearable style="width: 150px; margin-right: 10px">
        <el-option label="全部" value="" />
        <el-option label="电子产品" value="电子产品" />
        <el-option label="服装" value="服装" />
        <el-option label="食品" value="食品" />
        <el-option label="图书" value="图书" />
      </el-select>
      
      <el-button type="primary" @click="refreshProducts" :loading="loading">
        <el-icon><Refresh /></el-icon>
        刷新
      </el-button>
      
      <el-button 
        type="danger" 
        @click="batchDelete" 
        :disabled="selectedProducts.length === 0 || !canManage"
        style="margin-left: 10px;"
      >
        <el-icon><Delete /></el-icon>
        批量删除 ({{ selectedProducts.length }})
      </el-button>
    </div>

    <!-- 商品列表 -->
    <div class="product-table">
      <el-table 
        :data="products" 
        border 
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="商品名称" min-width="200" />
        <el-table-column prop="price" label="价格" width="100">
          <template #default="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column prop="stock" label="库存" width="80" />
        <el-table-column prop="sellerId" label="卖家ID" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewProduct(scope.row.id)">查看</el-button>
            <el-button 
              size="small" 
              type="primary" 
              @click="editProduct(scope.row)"
              :disabled="!canEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="deleteProduct(scope.row.id)"
              :disabled="!canDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container" v-if="total > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑商品对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      :before-close="handleDialogClose"
    >
      <el-form :model="productForm" :rules="rules" ref="productFormRef" label-width="100px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="productForm.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input-number 
            v-model="productForm.price" 
            :min="0.01" 
            :precision="2" 
            :step="0.01"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="商品分类" prop="category">
          <el-select v-model="productForm.category" placeholder="请选择分类" style="width: 100%">
            <el-option label="电子产品" value="电子产品" />
            <el-option label="服装" value="服装" />
            <el-option label="食品" value="食品" />
            <el-option label="图书" value="图书" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品库存" prop="stock">
          <el-input-number 
            v-model="productForm.stock" 
            :min="0" 
            :precision="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="商品图片" prop="image">
          <ImageUploader 
            v-model="productForm.image"
            @upload-success="handleImageUploadSuccess"
            @upload-error="handleImageUploadError"
            @remove="handleImageRemove"
          />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input 
            v-model="productForm.description" 
            type="textarea" 
            :rows="4"
            placeholder="请输入商品描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitProduct" :loading="submitting">
            {{ isEdit ? '更新' : '添加' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import request from '@/utils/request';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Search, Refresh, Delete } from '@element-plus/icons-vue';
import ImageUploader from '@/components/ImageUploader.vue';

export default {
  name: 'ProductManagement',
  components: {
    Plus,
    Search,
    Refresh,
    Delete,
    ImageUploader
  },
  setup() {
    const router = useRouter();
    const userStore = useUserStore();
    
    const products = ref([]);
    const loading = ref(false);
    const submitting = ref(false);
    const dialogVisible = ref(false);
    const isEdit = ref(false);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const total = ref(0);
    const searchQuery = ref('');
    const categoryFilter = ref('');
    const selectedProducts = ref([]);
    const searchTimeout = ref(null);
    const productFormRef = ref(null);

    const productForm = ref({
      id: null,
      name: '',
      price: 0,
      category: '',
      stock: 0,
      image: '',
      description: ''
    });

    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入商品名称', trigger: 'blur' },
        { min: 2, max: 50, message: '商品名称长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      price: [
        { required: true, message: '请输入商品价格', trigger: 'blur' },
        { type: 'number', min: 0.01, message: '价格必须大于0', trigger: 'blur' }
      ],
      category: [
        { required: true, message: '请选择商品分类', trigger: 'change' }
      ],
      stock: [
        { required: true, message: '请输入商品库存', trigger: 'blur' },
        { type: 'number', min: 0, message: '库存不能小于0', trigger: 'blur' }
      ]
    };

    // 计算属性
    const dialogTitle = computed(() => isEdit.value ? '编辑商品' : '添加商品');
    const canManage = computed(() => userStore.user && userStore.user.role === 'admin');
    
    const canEdit = (product) => {
      return canManage.value || (userStore.user && product.sellerId === userStore.user.id);
    };
    
    const canDelete = (product) => {
      return canManage.value || (userStore.user && product.sellerId === userStore.user.id);
    };

    // 图片上传相关方法
    const handleImageUploadSuccess = (imageUrl) => {
      ElMessage.success('图片上传成功！');
    };

    const handleImageUploadError = (error) => {
      ElMessage.error('图片上传失败：' + error);
    };

    const handleImageRemove = () => {
      ElMessage.info('图片已移除');
    };

    // 获取商品列表
    const fetchProducts = async () => {
      loading.value = true;
      try {
        const params = {
          page: currentPage.value,
          size: pageSize.value,
          search: searchQuery.value,
          category: categoryFilter.value
        };
        
        const response = await request.get('/api/products', { params });
        if (response.code === 200) {
          products.value = response.data.records;
          total.value = response.data.total;
        }
      } catch (error) {
        console.error('获取商品列表失败:', error);
        ElMessage.error('获取商品列表失败');
      } finally {
        loading.value = false;
      }
    };

    // 搜索处理
    const handleSearch = () => {
      if (searchTimeout.value) {
        clearTimeout(searchTimeout.value);
      }
      searchTimeout.value = setTimeout(() => {
        currentPage.value = 1;
        fetchProducts();
      }, 500);
    };

    // 刷新商品列表
    const refreshProducts = () => {
      fetchProducts();
    };

    // 显示添加对话框
    const showAddDialog = () => {
      isEdit.value = false;
      productForm.value = {
        id: null,
        name: '',
        price: 0,
        category: '',
        stock: 0,
        image: '',
        description: ''
      };
      dialogVisible.value = true;
    };

    // 编辑商品
    const editProduct = (product) => {
      isEdit.value = true;
      productForm.value = { ...product };
      dialogVisible.value = true;
    };

    // 提交商品
    const submitProduct = async () => {
      if (!productFormRef.value) return;
      
      try {
        await productFormRef.value.validate();
        submitting.value = true;
        
        const url = isEdit.value ? `/api/products/${productForm.value.id}` : '/api/products';
        const method = isEdit.value ? 'put' : 'post';
        
        const response = await request[method](url, productForm.value);
        
        if (response.code === 200) {
          ElMessage.success(isEdit.value ? '商品更新成功' : '商品添加成功');
          dialogVisible.value = false;
          fetchProducts();
        } else {
          ElMessage.error(response.message || '操作失败');
        }
      } catch (error) {
        console.error('提交商品失败:', error);
        ElMessage.error('操作失败');
      } finally {
        submitting.value = false;
      }
    };

    // 删除商品
    const deleteProduct = async (id) => {
      try {
        await ElMessageBox.confirm('确定要删除这个商品吗？', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        const response = await request.delete(`/api/products/${id}`);
        if (response.code === 200) {
          ElMessage.success('商品删除成功');
          fetchProducts();
        } else {
          ElMessage.error(response.message || '删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除商品失败:', error);
          ElMessage.error('删除失败');
        }
      }
    };

    // 批量删除
    const batchDelete = async () => {
      if (selectedProducts.value.length === 0) {
        ElMessage.warning('请选择要删除的商品');
        return;
      }
      
      try {
        await ElMessageBox.confirm(
          `确定要删除选中的 ${selectedProducts.value.length} 个商品吗？`, 
          '确认批量删除', 
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );
        
        const ids = selectedProducts.value.map(p => p.id);
        const response = await request.delete('/api/products/batch', { data: { ids } });
        
        if (response.code === 200) {
          ElMessage.success('批量删除成功');
          selectedProducts.value = [];
          fetchProducts();
        } else {
          ElMessage.error(response.message || '批量删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除失败:', error);
          ElMessage.error('批量删除失败');
        }
      }
    };

    // 查看商品详情
    const viewProduct = (id) => {
      router.push(`/product/${id}`);
    };

    // 选择变化处理
    const handleSelectionChange = (selection) => {
      selectedProducts.value = selection;
    };

    // 分页处理
    const handleSizeChange = (size) => {
      pageSize.value = size;
      currentPage.value = 1;
      fetchProducts();
    };

    const handleCurrentChange = (page) => {
      currentPage.value = page;
      fetchProducts();
    };

    // 对话框关闭处理
    const handleDialogClose = () => {
      dialogVisible.value = false;
    };

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN');
    };

    // 页面加载时获取数据
    onMounted(() => {
      fetchProducts();
    });

    return {
      products,
      loading,
      submitting,
      dialogVisible,
      isEdit,
      currentPage,
      pageSize,
      total,
      searchQuery,
      categoryFilter,
      selectedProducts,
      productFormRef,
      productForm,
      rules,
      dialogTitle,
      canManage,
      canEdit,
      canDelete,
      handleImageUploadSuccess,
      handleImageUploadError,
      handleImageRemove,
      fetchProducts,
      handleSearch,
      refreshProducts,
      showAddDialog,
      editProduct,
      submitProduct,
      deleteProduct,
      batchDelete,
      viewProduct,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange,
      handleDialogClose,
      formatDate
    };
  }
};
</script>

<style scoped>
.product-management-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 10px;
}

.product-table {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .product-management-container {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }
  
  .search-bar {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .search-bar .el-input {
    width: 100% !important;
    margin-right: 0 !important;
  }
}
</style> 